﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MySql.Data.MySqlClient;
using System;
using System.IO;
using System.Text;

namespace B.S.NewMedical.Api.Write.Controllers.MySqlHuifu
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DatabaseMySqlController : ControllerBase
    {
        /// <summary>
        /// 备份数据库
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="backupFilePath">文件路径</param>
        [HttpPost]
        public IActionResult BackupDatabase(string connectionString, string backupFilePath)
        {
            try
            {
                // 验证连接字符串
                if (string.IsNullOrEmpty(connectionString))
                {
                    return BadRequest("连接字符串不能为空");
                }

                // 如果未指定备份路径，使用默认路径
                if (string.IsNullOrEmpty(backupFilePath))
                {
                    string defaultBackupDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Backups");
                    if (!Directory.Exists(defaultBackupDir))
                    {
                        Directory.CreateDirectory(defaultBackupDir);
                    }
                    backupFilePath = Path.Combine(defaultBackupDir, $"backup_{DateTime.Now:yyyyMMdd_HHmmss}.sql");
                }
                else
                {
                    // 确保备份目录存在
                    string backupDir = Path.GetDirectoryName(backupFilePath);
                    if (!string.IsNullOrEmpty(backupDir) && !Directory.Exists(backupDir))
                    {
                        Directory.CreateDirectory(backupDir);
                    }
                }

                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;

                    // 创建备份实例
                    MySqlBackup backup = new MySqlBackup(cmd);

                    // 执行备份并保存到文件
                    backup.ExportToFile(backupFilePath);
                }

                return Ok(new { message = "数据库备份成功", backupFilePath = backupFilePath });
            }
            catch (UnauthorizedAccessException ex)
            {
                return BadRequest($"权限不足，无法访问路径: {ex.Message}");
            }
            catch (Exception ex)
            {
                return BadRequest($"备份失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 还原数据库
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="backupFilePath">文件路径</param>
        [HttpPost]
        public IActionResult RestoreDatabase(string connectionString, string backupFilePath)
        {
            try
            {
                // 验证连接字符串
                if (string.IsNullOrEmpty(connectionString))
                {
                    return BadRequest("连接字符串不能为空");
                }

                // 验证备份文件是否存在
                if (string.IsNullOrEmpty(backupFilePath) || !System.IO.File.Exists(backupFilePath))
                {
                    return BadRequest("备份文件不存在或路径无效");
                }

                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection = conn;

                    // 创建还原实例
                    MySqlBackup restore = new MySqlBackup(cmd);

                    // 从文件导入数据
                    restore.ImportFromFile(backupFilePath);
                }

                return Ok(new { message = "数据库还原成功" });
            }
            catch (UnauthorizedAccessException ex)
            {
                return BadRequest($"权限不足，无法访问文件: {ex.Message}");
            }
            catch (Exception ex)
            {
                return BadRequest($"还原失败: {ex.Message}");
            }
        }
    }
}
